<template>
  <div class="file-box" v-for="(item, index) in newFileList" :key="index">
    <div class="file-item">
      <img :src="item.url" :alt="item.name" />
      <span>{{ item.name }}</span>
    </div>

    <div class="file-btns">
      <el-button v-if="isDown" type="primary" text @click="handleDown(item)"> 下载 </el-button>
      <Upload :tip-show="false" :multiple="false" @upload-success="uploadSuccess($event, item)">
        <template #upload-btn>
          <el-icon>
            <Refresh />
          </el-icon>
        </template>
      </Upload>
    </div>
  </div>
</template>
<script setup lang="ts" name="UploadBasics">
import { computed, ref } from 'vue'
import type { UploadUserFile } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import Upload from './Upload.vue'

interface UploadFileProps {
  fileList: any[] // 文件列表
  uploadList?: UploadUserFile[] // 上传列表
}

const { fileList, uploadList = [] } = defineProps<UploadFileProps>()

const isDown = ref(true) // 是否显示下载按钮

const newFileList = computed(() => {
  return [...fileList, ...uploadList]
})

const handleDown = (item: any) => {
  console.log('下载文件', item);
}

const uploadSuccess = (e: { uploadLatestFile: UploadUserFile }, item: any) => {
  const { uploadLatestFile } = e
  // 这里名称保持唯一，生成规则不限
  const idx_1 = uploadList.findIndex((v: any) => v.name === item.name)
  if (idx_1 > -1) {
    uploadList.splice(idx_1, 1, uploadLatestFile)
  }

  const idx_2 = fileList.findIndex((v: any) => v.name === item.name)
  if (idx_2 > -1) {
    fileList.splice(idx_2, 1, uploadLatestFile)
  }

}

defineExpose({
  newFileList,
  uploadSuccess,
  handleDown,
})
</script>
<style lang="scss" scoped>
.file-box {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #e6e6e6;
}

.file-item {
  display: flex;
  align-items: center;
}

.file-btns {
  display: flex;
  align-items: center;
}

img {
  width: 80px;
  height: 40px;
  border-radius: 8px;
  margin-right: 10px;
}
</style>
